#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/9/6 11:11
# @File           : __init__
# @IDE            : PyCharm
# @desc           : 描述

from datetime import datetime
from sqlalchemy.orm import joinedload
from fastapi import APIRouter, Depends
from utils.response import SuccessResponse
from core.dependencies import IdList
from core.exception import CustomException
from apps.base.auth.validate import AllUserAuth, Auth
from . import schemas, crud, params, models


app = APIRouter()


@app.get("/order", summary="获取Order表单")
async def get_order(
        p: params.OrderParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    datas, count = await crud.OrderDal(auth.db).get_datas(
        **p.dict(),
        v_schema=schemas.OrderSimpleOut,
        v_return_count=True
    )
    return SuccessResponse(datas, count=count)

@app.get("/order/{data_id}", summary="获取Order表单详情")
async def get_order_detail(
        data_id: int,
        auth: Auth = Depends(AllUserAuth())
):
    return SuccessResponse(await crud.OrderDal(auth.db).get_data(
        data_id=data_id, v_schema=schemas.OrderOut,
        v_options=[joinedload(models.DCOrder.contents), joinedload(models.DCOrder.progresses)])
    )


@app.post("/order", summary="创建Order表单")
async def create_order(
        data: schemas.Order,
        auth: Auth = Depends(AllUserAuth())
):
    return SuccessResponse(await crud.OrderDal(auth.db).create_data(data))


@app.put("/order/{data_id}", summary="更新Order表单")
async def put_order(
        data_id: int,
        data: schemas.OrderUpdate,
        auth: Auth = Depends(AllUserAuth())

):
    return SuccessResponse(await crud.OrderDal(auth.db).put_data(data_id, data=data.model_dump(exclude_none=True)))


@app.put("/order/{data_id}/stamp", summary="Order表单刷卡")
async def put_order_stamp(
        data_id: int,
        data: schemas.OrderStampType,
        auth: Auth = Depends(AllUserAuth())
):
    obj = await crud.OrderDal(auth.db).get_data(data_id=data_id)
    if data.type == "prepared_by":
        obj.prepared_by = auth.user.user_str
        obj.prepared_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        obj.prepared_dept = f"{auth.user.employeeCode}({auth.user.employeeId})"
    elif data.type == "approved_by":
        obj.approved_by = auth.user.user_str_time
    elif data.type == "received_by":
        obj.received_by = auth.user.user_str_time
    elif data.type == "feeded_by":
        obj.feeded_by = auth.user.user_str_time

    await crud.OrderDal(auth.db).flush(obj)
    return SuccessResponse("更新成功")


@app.put("/order/{data_id}/status", summary="更新Order表单状态")
async def put_order_status(
        data_id: int,
        data: schemas.OrderUpdateStatus,
        auth: Auth = Depends(AllUserAuth())

):
    obj = await crud.OrderDal(auth.db).get_data(data_id=data_id)
    if obj.status == "归档":
        raise CustomException("归档委托单不允许更新状态")
    if data.status and data.status == '作废':
        obj.status = '作废'
    else:
        if obj.status == "计划中":
            obj.status = '实验中'
        elif obj.status == '实验中':
            if data.status and data.status == "等待其他实验":
                obj.status = '实验中'
            else:
                obj.status = '审核中'
        elif obj.status == '审核中':
            obj.status = '归档'
            obj.finished_date = datetime.now()
            
    await crud.OrderDal(auth.db).flush(obj)
    return SuccessResponse("更新成功")


@app.delete("/order", summary="批量删除Order表单", description="软删除")
async def delete_order(ids: IdList = Depends(), auth: Auth = Depends(AllUserAuth())):
    await crud.OrderDal(auth.db).delete_datas(ids=ids.ids, v_soft=True, delete_user=auth.user.user_str)
    return SuccessResponse("删除成功")


# @app.get("/order/{data_id}/progress", summary="获取Order表单进度")
# async def get_order_progress(
#         data_id: int,
#         auth: Auth = Depends(AllUserAuth())
# ):
#     datas, count = await crud.OrderProgressDal(auth.db).get_datas(
#         order_id=data_id,
#         v_return_count=True
#     )
#     return SuccessResponse(datas, count=count)


@app.post("/order/progress", summary="创建Order表单进度")
async def create_order_progress(
        data: schemas.OrderProgress,
        auth: Auth = Depends(AllUserAuth())
):
    data.create_user = auth.user.user_str
    return SuccessResponse(await crud.OrderProgressDal(auth.db).create_data(data))


@app.post("/order/content", summary="创建Order实验结果")
async def create_order_content(
        data: schemas.OrderContent,
        auth: Auth = Depends(AllUserAuth())
):
    obj = await crud.OrderDal(auth.db).get_data(data_id=data.order_id)
    if obj.status != '实验中':
        raise CustomException("该状态委托单不允许增加实验结果")
    data.create_user = auth.user.user_str
    data.test_performed_by = auth.user.user_str_time
    return SuccessResponse(await crud.OrderContentDal(auth.db).create_data(data))


@app.delete("/order/{data_id}/content", summary="删除Order实验结果", description="软删除")
async def delete_order_content(
        data_id: int,
        ids: IdList = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    obj = await crud.OrderDal(auth.db).get_data(data_id=data_id)
    if obj.status != '实验中':
        raise CustomException("该状态委托单不允许删除实验结果")
    await crud.OrderContentDal(auth.db).delete_datas(ids=ids.ids, v_soft=True, delete_user=auth.user.user_str)
    return SuccessResponse("删除成功")
